from OWRpy import * 
import redRGUI 
from OWRpy import * 
import redRGUI 
import redRi18n
_ = redRi18n.get_(package = 'base')

#widget code
class outliersUni(OWRpy): 
    globalSettingsList = ['commit']
    def __init__(self, **kwargs):
        OWRpy.__init__(self, **kwargs)
        self.data = {}
        self.RFunctionParam_object = ''
        
        #input
        self.inputs.addInput('id0', _('R Variable Object'), signals.base.RDataFrame, self.processobject)
        
        #Unique R variables
        self.setRvariableNames(["selectedColumn"])
        self.setRvariableNames(["outlierTest"])
        
        #GUI
        area = redRGUI.base.widgetBox(self.controlArea,orientation='vertical')  
        toparea = redRGUI.base.widgetBox(area,orientation='horizontal')  
        options = redRGUI.base.widgetBox(toparea,orientation='vertical')
 
        self.namesList = redRGUI.base.listBox(toparea, label = _('Select element'))
        self.namesList.setSelectionMode(QAbstractItemView.SingleSelection)
 
        self.methodButtons = redRGUI.base.comboBox(options,  label = "Select test",
        items = [('chisq.out.test','Chi-squared'),
        #('cochran.test','Cochran'),
        ('dixon.test','Dixon'),
        ('grubbs.test','Grubbs'),
        ('outlier','Largest difference from the mean')],
        editable=False, callback = self.onTestChange)
        
        textBoxWidth = 50
        self.testOptions = redRGUI.base.widgetBox(options)
        
        self.chisq = redRGUI.base.groupBox(self.testOptions,label='Options')
        self.chisqOpp = redRGUI.base.lineEdit(self.chisq, label='Opposite', id='opposite', text='FALSE', width=textBoxWidth)
        self.chisqVar = redRGUI.base.lineEdit(self.chisq, label='Population variance (leave blank if unknown)',id='variance', text='',width=textBoxWidth)
        
        #self.cochran = groupBox(self.testOptions, label='Options')
        #self.cochranInl = redRGUI.base.lineEdit(self.cochran, label='Inlying', id='inlying', text='FALSE', width=textBoxWidth)
        #self.cochran.hide()

        self.dixon = redRGUI.base.groupBox(self.testOptions,label='Options')
        self.dixonOpp = redRGUI.base.lineEdit(self.dixon, label='Opposite', id='opposite', text='FALSE', width=textBoxWidth)
        self.dixonType = redRGUI.base.lineEdit(self.dixon, label='Test variant [0,10,11,12,20,21]', id='type', text='0', width=textBoxWidth)
        self.dixonSide = redRGUI.base.lineEdit(self.dixon, label='Two-sided', id='two.sided', text='TRUE', width=textBoxWidth)
        self.dixon.hide()        

        self.grubbs = redRGUI.base.groupBox(self.testOptions,label='Options')
        self.grubbsOpp = redRGUI.base.lineEdit(self.grubbs, label='Opposite', id='opposite', text='FALSE', width=textBoxWidth)
        self.grubbsType = redRGUI.base.lineEdit(self.grubbs, label='Test variant [10,11,20]', id='type', text='10', width=textBoxWidth)
        self.grubbsSide = redRGUI.base.lineEdit(self.grubbs, label='Two-sided', id='two.sided', text='FALSE', width=textBoxWidth)
        self.grubbs.hide()
        
        self.outlier = redRGUI.base.groupBox(self.testOptions,label='Options')
        self.outlierOpp = redRGUI.base.lineEdit(self.outlier, label='Opposite', id='opposite', text='FALSE', width=textBoxWidth)
        self.outlier.hide()
        
        # Commit
        self.commit = redRGUI.base.commitButton(self.bottomAreaRight, _("Commit"), alignment=Qt.AlignLeft, 
        callback = self.commitFunction, processOnInput=True)
        self.RoutputWindow = redRGUI.base.textEdit(self.controlArea, label = _("RoutputWindow"))
        
    def onTestChange(self):
        for i in self.testOptions.findChildren(groupBox):
            i.setHidden(True)
        # print self.distOptions.findChild(self.methodButtons.currentId(),widgetBox)
        # self.distOptions.findChild(widgetBox,self.methodButtons.currentId()).show()
      
        if self.methodButtons.currentId() == 'chisq.out.test':
            self.chisq.show()
        #elif self.methodButtons.currentId() == 'cochran.test':
        #    self.cochran.show()
        elif self.methodButtons.currentId() == 'dixon.test':
            self.dixon.show()
        elif self.methodButtons.currentId() == 'grubbs.test':
            self.grubbs.show()
        elif self.methodButtons.currentId() == 'outlier':
            self.outlier.show()
                   
        
    def processobject(self, data):
        if not self.require_librarys(["outliers"]):
            self.status.setText('R Libraries Not Loaded.')
            return
        if data:
            self.RFunctionParam_object=data.getData()
            self.data = data
            self.namesList.update(self.R('names('+self.RFunctionParam_object+')', wantType = 'list'))
            if self.commit.processOnInput():
                self.commitFunction()
        else:
            self.RFunctionParam_object=''
    
    def collectParameters(self):
        self.injection = []
        test = unicode(self.methodButtons.currentId())
        if test =='chisq.out.test':
            self.injection.append('%s=%s' % (self.chisqOpp.widgetId(), self.chisqOpp.text()))
            if self.chisqOpp.text() == '':
                print 'Population variance unknown'
            else:
                self.injection.append('%s=%s' % (self.chisqVar.widgetId(), self.chisqVar.text()))
        #elif dist =='cochran.test':
        #    self.injection.append('%s=%s' % (self.cochranInl.widgetId(), self.cochranInl.text()))
        elif test == 'dixon.test':
            self.injection.append('%s=%s' % (self.dixonOpp.widgetId(), self.dixonOpp.text()))
            self.injection.append('%s=%s' % (self.dixonType.widgetId(), self.dixonType.text()))
            self.injection.append('%s=%s' % (self.dixonSide.widgetId(), self.dixonSide.text()))
        elif test == 'grubbs.test':
            self.injection.append('%s=%s' % (self.grubbsOpp.widgetId(), self.grubbsOpp.text()))
            self.injection.append('%s=%s' % (self.grubbsType.widgetId(), self.grubbsType.text()))
            self.injection.append('%s=%s' % (self.grubbsSide.widgetId(), self.grubbsSide.text()))
        elif test == 'outlier':
            self.injection.append('%s=%s' % (self.outlierOpp.widgetId(), self.outlierOpp.text()))
        
        return self.injection    
    
    def commitFunction(self):
        
        if unicode(self.RFunctionParam_object) == '':
            return
        if len(self.namesList.selectedItems()) == 0:
            self.status.setText('Choose a variable in the list')
            return
        else:
            self.status.setText('Data processing...')
        
        # get data from the selected item
        self.R(self.Rvariables['selectedColumn']+'<-'+unicode(self.RFunctionParam_object)+'[,'+unicode(self.namesList.row(self.namesList.currentItem())+1)+']')
        
        
        # START COLLECTION THE R PARAMETERS THAT WILL CREATE THE R CODE TO EXECUTE
        test = unicode(self.methodButtons.currentId())
        self.injection = self.collectParameters()
        
        # combine all the parameters in the a string    
        inj = ','.join(self.injection)
        
        # make the R call. The results will be saved in the 'cor' variable we declared earlier
        self.R('%s <- %s(%s, %s)' % (self.Rvariables['outlierTest'], test, self.Rvariables['selectedColumn'], inj), wantType = 'NoConversion')
        
        if self.methodButtons.currentId() in ['chisq.out.test','dixon.test']:           
            tmp = self.R('paste("<u>Data name</u>: ", '+self.Rvariables['outlierTest']+'$data.name,"\n", "<u>Method</u>: ",'+self.Rvariables['outlierTest']+'$method,"\n", "<u>Test statistic</u>: ", '+self.Rvariables['outlierTest']+'$statistic,"\n","<u>p-value</u>: ", '+self.Rvariables['outlierTest']+'$p.value, "\n", "<u>Alternative</u>: ", '+self.Rvariables['outlierTest']+'$alternative, collapse ="\n")')
        if self.methodButtons.currentId() == 'grubbs.test':
            tmp = self.R('paste("<u>Data name</u>: ", '+self.Rvariables['outlierTest']+'$data.name,"\n", "<u>Method</u>: ",'+self.Rvariables['outlierTest']+'$method,"\n", "<u>Test statistic G</u>: ", '+self.Rvariables['outlierTest']+'$statistic[1],"\n", "<u>Test statistic U</u>: ", '+self.Rvariables['outlierTest']+'$statistic[2],"\n","<u>p-value</u>: ", '+self.Rvariables['outlierTest']+'$p.value, "\n", "<u>Alternative</u>: ", '+self.Rvariables['outlierTest']+'$alternative, collapse ="\n")')
        elif self.methodButtons.currentId() == 'outlier':       
            tmp = self.R('paste("<u>A vector of value(s) with largest difference from the mean</u>: ", '+self.Rvariables['outlierTest']+', collapse ="\n")')
            
        self.RoutputWindow.clear()
        self.RoutputWindow.insertHtml('<br><pre>'+tmp+'</pre>')
        self.status.setText('Data processed.')